#!/usr/bin/python
# -*- coding:utf-8 -*-pipi
from io import BytesIO
import requests as req
import json
from PIL import Image, ImageDraw, ImageFont
import os


baseUrl = "https://gitee.com/savagecm/epaper-python/raw/master/"
image = Image.new(mode='1', size=(1304, 984), color=(1))
picLocation = ""
epaper_url = ""
epaper_name = ""


def read_file(location):
    res = req.get(location)
    print("get file with content :" + res.text)
    return res.text


def text_wrap(text, font, max_higth, max_width):
    lines = []
    line_index = 1
    text_list = text.splitlines()
    for line in text_list:
        print("process line : "+line)
        line_height = font.getsize(line)[1]
        line_width = font.getsize(line[0:1])[0]
        if line_width == 0:
            continue
        word_per_line = max_width//line_width
        print("font width and height : "+str(line_height)+":"+str(line_width))
        if line_index*line_height <= max_higth:
            line_number = font.getsize(line)[0]//max_width
            if (line_number-line_index)*line_height > max_higth:
                line_number = max_higth//line_height-line_index
            print("line num is : "+str(line_number))
            if line_number > 0:
                line_index += line_number
                for i in range(0, line_number+1):
                    lines.append(line[int(i*word_per_line)                                      : int((i+1)*word_per_line)])
            elif line_number == 0:
                lines.append(line)
                line_index += 1
        else:
            print("larger than max height!")
    return lines


def draw_text_list(draw, window, font, data_list):
    for data in data_list:
        window = draw_text(draw, window, font, data)
    return window


def draw_text(draw, window, font, data):
    posx = window["position"]["posx"]
    posy = window["position"]["posy"]
    height = window["hight"]
    width = window["width"]
    lines = text_wrap(data, font, height, width)
    line_height = font.getsize('hg')[1]
    tmp_posy = posy
    for line in lines:
        # draw the line on the image
        draw.text((posx, tmp_posy), line, fill=(0), font=font)
        # update the y position so that we can use it for next line
        tmp_posy = tmp_posy + line_height
    print("next posy is "+str(tmp_posy))
    window["position"]["posy"] = window["position"]["posy"] + \
        len(lines*line_height)
    window["hight"] = window["hight"]-len(lines)*line_height
    return window


def draw_window(draw, window):
    height = window["hight"]
    width = window["width"]
    posx = window["position"]["posx"]
    posy = window["position"]["posy"]
    coords = [(posx, posy), (posx, posy+height),
              (posx+width, posy+height), (posx+width, posy)]
    draw.polygon(coords, outline=(0))


def get_font(size):
    ttf_path = "fonts/simhei.ttf"
    ttf = ImageFont.truetype(ttf_path, size)
    return ttf


def process_glob_config(draw):
    json_data = read_file(baseUrl+"globConfig.json")
    text = json.loads(json_data)
    for cfg in text:
        if cfg["type"] == "fileName":
            print("in fileurl case")
            file_json = read_file(baseUrl + cfg["data"])
            file_datas = json.loads(file_json)
            window = cfg["window"]
            draw_window(draw, window)
            for file_data in file_datas:
                if file_data["type"] == "raw":
                    print("print raw ")
                    font = get_font(file_data["font"])
                    window = draw_text(
                        draw, window, font, file_data["data"])
                elif file_data["type"] == "file":
                    print("file")
                    font = get_font(file_data["font"])
                    window = draw_text(
                        draw, window, font, read_file(baseUrl+file_data["data"]))
                else:
                    print("unsupport type")
        elif cfg["type"] == "picName":
            print("in picName case")
            name = cfg["data"]
            window = cfg["window"]
            url = baseUrl+"pic/"+name
            print("url is :"+url)
            response = req.get(url)
            qrimage = Image.open(BytesIO(response.content))
            qrimage.resize((window["hight"], window["width"]))
            image.paste(qrimage, (window["position"]["posx"], window["position"]["posy"],
                                  window["position"]["posx"] + window["width"], window["position"]["posy"]+window["hight"]))
        elif cfg["type"] == "dailySentence":
            print("in dailySentenceCiba case")
            name = cfg["data"]
            window = cfg["window"]
            draw_window(draw, window)
            data = read_file(baseUrl+name)
            print("dailySentence"+data)
            sentences = json.loads(data)
            for sentence in sentences:
                text_list = []
                font = get_font(sentence["font"])
                url = sentence["url"]
                sentence_rsp = json.loads(read_file(url))
                data_list = sentence["data"]
                for data_disp in data_list:
                    if data_disp in sentence_rsp:
                        text_list.append(sentence_rsp[data_disp])
                    elif "data" in sentence_rsp:
                        text_list.append(sentence_rsp["data"][data_disp])
                    else:
                        print("invalid data!"+data_disp)
                text_list.append("----------")
                window = draw_text_list(
                    draw, window, font, text_list)
        elif cfg["type"] == "epaper":
            name = cfg["data"]
            data = read_file(baseUrl+name)
            epaper_data = json.loads(data)
            global epaper_url
            global picLocation
            global epaper_name
            epaper_url = epaper_data["url"]
            picLocation = epaper_data["picLocation"]
            epaper_name = epaper_data["picName"]
        else:
            print("not support type")


def main():
    draw = ImageDraw.Draw(im=image)
    process_glob_config(draw)
    image.convert("1")
    # image.show()
    os.chdir(picLocation)
    image.save(epaper_name, 'bmp')
    # send message to epaper
    data = {}
    data["location"] = picLocation+'/'+epaper_name
    data["position"] = [0, 0]

    aheaders = {'Content-Type': 'application/json'}

    body = json.dumps(data)
    # 字符串格式
    print("json body is : "+body)
    res = req.post(url=epaper_url+"/image", headers=aheaders, data=body)
    print("response: "+str(res.status_code)+":"+res.text)

    display_url = epaper_url+"/display"
    res = req.post(url=display_url, headers=aheaders)
    print("display response: "+str(res.status_code)+":"+res.text)


if __name__ == '__main__':
    main()
